/**
 * @link https://leetcode.cn/problems/valid-parentheses/?envType=study-plan-v2&envId=top-interview-150
 */
function isValid(s: string): boolean {
  let st = [s[0]];
  let end = 1;
  while (end < s.length) {
    if (s[end] === ")" && st[st.length - 1] === "(") {
      end += 1;
      st.pop();
    } else if (s[end] === "]" && st[st.length - 1] === "[") {
      end += 1;
      st.pop();
    } else if (s[end] === "}" && st[st.length - 1] === "{") {
      end += 1;
      st.pop();
    } else {
      st.push(s[end]);
      end += 1;
    }
  }

  return !st.length;
}

/**
 * @link https://leetcode.cn/problems/simplify-path/?envType=study-plan-v2&envId=top-interview-150
 */
function simplifyPath(path: string): string {
  let ans: string[] = [];
  // 存储文件名称
  let tmp = "";
  let end = 0;
  while (end < path.length) {
    if (path[end] === "/") {
      while (end + 1 < path.length && path[end + 1] === "/") {
        end += 1;
      }
      end += 1;
      while (end < path.length && path[end] !== "/") {
        tmp += path[end];
        end += 1;
      }
      console.log(tmp);
      if (tmp === "." || tmp === "") {
      } else if (tmp === "..") {
        ans.pop();
      } else {
        ans.push(tmp);
      }
      tmp = "";
    }
    console.log(ans);
  }
  console.log("/" + ans.join("/"));

  return "/" + ans.join("/");
}

/**
 * @link https://leetcode.cn/problems/min-stack/?envType=study-plan-v2&envId=top-interview-150
 */
class MinStack {
  constructor() {}

  push(val: number): void {}

  pop(): void {}

  top(): number {
    return 0;
  }

  getMin(): number {
    return 0;
  }
}
/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(val)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

/**
 * @link https://leetcode.cn/problems/evaluate-reverse-polish-notation/?envType=study-plan-v2&envId=top-interview-150
 */
function evalRPN(tokens: string[]): number {
  const handleCaculation = (a: number, b: number, cmp: string): number => {
    switch (cmp) {
      case "+":
        return a + b;
      case "-":
        return a - b;
      case "*":
        return a * b;
      case "/":
        return parseInt((a / b).toString());
    }
    return 0;
  };
  let st: number[] = [];
  for (let i = 0; i < tokens.length; i++) {
    if (!isNaN(Number(tokens[i]))) {
      st.push(Number(tokens[i]));
    } else {
      const b = st.pop();
      const a = st.pop();
      console.log(a, b, tokens[i]);

      if (a !== undefined && b !== undefined && tokens[i]) {
        st.push(handleCaculation(a, b, tokens[i]));
      }
    }
  }
  console.log(st);
  return st[0];
}

export default { isValid, simplifyPath, evalRPN };
